package com.hzp.lolnews.ui.friends.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hzp.lolnews.R;
import com.hzp.lolnews.ui.novel.adapter.FridAdapter;
import com.hzp.lolnews.ui.novel.bean.FridBean;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class FXFragment extends Fragment{

    private FridAdapter adapter;
    private XRecyclerView xRecycler;
    private String path;

    public FXFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fx, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化控件
        initView(view);
        Bundle bundle = getArguments();
        path = bundle.getString("path");
        //加载数据
        getData(false, path);
    }

    private void initView(View view) {
        xRecycler = (XRecyclerView)view.findViewById(R.id.frid_recyclerView);
        assert xRecycler != null;
        adapter = new FridAdapter();
        xRecycler.setAdapter(adapter);
    }

    private void getData(final boolean isMore, final String url) {
        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        xRecycler.setLayoutManager(manager1);
        Observable.create(new Observable.OnSubscribe<String>(){
            @Override
            public void call(final rx.Subscriber<? super String> subscriber) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().get().url(url).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            String data = response.body().string();
                            if(data.length() > 0 ){
                                subscriber.onNext(data);
                                subscriber.onCompleted();
                            }else{
                                Toast.makeText(getActivity(),"数据为空!",Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<String>() {
            @Override
            public void call(String data) {
                try {
                    JSONObject da = new JSONObject(data);
                    JSONObject ob = da.getJSONObject("data");
                    JSONArray array = ob.getJSONArray("rows");
                    Gson gson = new Gson();
                    List<FridBean.DataBean.RowsBean>  tData = gson.fromJson(array.toString(), new TypeToken<List<FridBean.DataBean.RowsBean>>() {
                    }.getType());
                    if (isMore) {
                        adapter.setMoreData(tData);
                    } else {
                        adapter.setData(tData);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //上下拉刷新
        xRecycler.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData(false, path);
                xRecycler.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                int date = 25;
                if(date > 0){
                    date--;
                    String json = 2016 + "-" + 10 + "-" + date;
                    getData(true,path + json);
                    xRecycler.loadMoreComplete();

                }else{
                    Toast.makeText(getActivity(),"没有数据了!",Toast.LENGTH_LONG).show();
                }

            }
        });
    }
}
